package models

import (
	"errors"
	"fmt"
	"image-server/config"
	"image-server/dao/model"
	"time"
)

// GetSharesByUserID 获取用户的所有分享记录（简化版）
func GetSharesByUserID(userID int64, page, limit int) ([]model.Share, int64, error) {
	// 处理分页偏移量
	offset := (page - 1) * limit
	if page <= 0 {
		offset = 0
	}

	// 查询总数
	var total int64
	if err := config.DB.QueryRow("SELECT COUNT(*) FROM shares WHERE user_id = ?", userID).Scan(&total); err != nil {
		return nil, 0, fmt.Errorf("统计总数失败: %w", err)
	}

	// 查询列表
	rows, err := config.DB.Query(`
        SELECT id, image_id, user_id, share_key, expires_at, created_at 
        FROM shares 
        WHERE user_id = ? 
        ORDER BY created_at DESC 
        LIMIT ? OFFSET ?
    `, userID, limit, offset)
	if err != nil {
		return nil, 0, fmt.Errorf("查询失败: %w", err)
	}
	defer rows.Close()
	var shares []model.Share
	for rows.Next() {
		var share model.Share
		var expiresAt, createdAt time.Time // 直接用time.Time接收数据库时间
		// 扫描数据（直接映射到时间类型，省去字符串转换）
		if err := rows.Scan(
			&share.ID, &share.ImageID, &share.UserID, &share.ShareKey,
			&expiresAt, &createdAt,
		); err != nil {
			return nil, 0, fmt.Errorf("扫描记录失败: %w", err)
		}

		// 赋值时间字段（按模型定义处理）
		share.ExpiresAt = expiresAt
		share.CreatedAt = createdAt.Format("2006-01-02 15:04:05")

		shares = append(shares, share)
	}

	// 检查行迭代错误
	if err := rows.Err(); err != nil {
		return nil, 0, fmt.Errorf("遍历记录失败: %w", err)
	}

	return shares, total, nil
}

// CreateShareWithKey 插入分享记录（使用传入的share_key）
func CreateShareWithKey(imageID, userID int64, shareKey string, expiresIn time.Duration) (*model.Share, error) {
	if shareKey == "" {
		return nil, errors.New("分享密钥不能为空")
	}
	// 计算过期时间
	expiresAt := time.Now().Add(expiresIn)
	// 插入数据库
	result, err := config.DB.Exec(`
        INSERT INTO shares (image_id, user_id, share_key, expires_at)
        VALUES (?, ?, ?, ?)
    `, imageID, userID, shareKey, expiresAt)
	if err != nil {
		return nil, fmt.Errorf("插入分享记录失败: %w", err)
	}

	id, err := result.LastInsertId()
	if err != nil {
		return nil, fmt.Errorf("获取分享记录ID失败: %w", err)
	}
	return &model.Share{
		ID:        id,
		ImageID:   imageID,
		UserID:    userID,
		ShareKey:  shareKey,
		ExpiresAt: expiresAt,
		CreatedAt: time.Now().Format("2006-01-02 15:04:05"),
	}, nil
}
